document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('canvas');
    const canvasContainer = document.querySelector('.canvas-container');
    const bubbles = [];
    const bubbleCount = 10;

    class Bubble {
        constructor(x, y, radius) {
            this.x = x;
            this.y = y;
            this.radius = radius;
            this.dx = (Math.random() - 0.5) * 2; // X方向速度
            this.dy = (Math.random() - 0.5) * 2; // Y方向速度
        }

        draw(ctx) {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(100, 150, 250, 0.6)';
            ctx.fill();
            ctx.closePath();
        }

        update() {
            this.x += this.dx;
            this.y += this.dy;

            // 碰撞检测
            if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
                this.dx = -this.dx;
            }
            if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
                this.dy = -this.dy;
            }
        }

        checkCollision(other) {
            const dx = this.x - other.x;
            const dy = this.y - other.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < this.radius + other.radius) {
                this.dx = -this.dx;
                this.dy = -this.dy;
                other.dx = -other.dx;
                other.dy = -other.dy;
            }
        }
    }

    const initBubbles = () => {
        for (let i = 0; i < bubbleCount; i++) {
            const radius = Math.random() * 20 + 10; // 随机半径
            const x = Math.random() * (canvas.width - radius * 2) + radius;
            const y = Math.random() * (canvas.height - radius * 2) + radius;
            bubbles.push(new Bubble(x, y, radius));
        }
    };

    const draw = () => {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        bubbles.forEach((bubble) => {
            bubble.update();
            bubble.draw(ctx);
        });

        // 碰撞检测
        for (let i = 0; i < bubbles.length; i++) {
            for (let j = i + 1; j < bubbles.length; j++) {
                bubbles[i].checkCollision(bubbles[j]);
            }
        }

        requestAnimationFrame(draw);
    };

    // 初始化画布和气泡
    const resizeCanvas = () => {
        canvas.width = canvasContainer.clientWidth;
        canvas.height = canvasContainer.clientHeight;
        bubbles.length = 0; // 清空气泡数组
        initBubbles();
    };

    window.addEventListener('resize', resizeCanvas);
    resizeCanvas(); // 初始化大小
    draw(); // 开始绘制
});
